package com.wenzhoujie.adapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.wenzhoujie.library.adapter.SDBaseAdapter;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.lingou.www.R;
import com.wenzhoujie.model.CommentMysActivityItemModel;
import com.wenzhoujie.utils.ViewHolder;

public class CommentMysAdapter extends SDBaseAdapter<CommentMysActivityItemModel>
{

	private Activity activity;

	public CommentMysAdapter(List<CommentMysActivityItemModel> listModel, Activity activity)
	{
		super(listModel, activity);
		this.activity = activity;

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null)
		{
			convertView = mInflater.inflate(R.layout.item_comment_mys, null);

		}

		ImageView ivUser_avatar = ViewHolder.get(convertView, R.id.item_comment_mys_iv_user_avatar);
		TextView tvUser_name = ViewHolder.get(convertView, R.id.item_comment_mys_tv_user_name);
		TextView tvList_time = ViewHolder.get(convertView, R.id.item_comment_mys_tv_time);
		TextView tvList_content = ViewHolder.get(convertView, R.id.item_comment_mys_tv_content);
		TextView tvList_scontent = ViewHolder.get(convertView, R.id.item_comment_mys_tv_scontent);

		final CommentMysActivityItemModel model = getItem(position);

		if (model != null)
		{
			SDViewBinder.setImageView(ivUser_avatar, model.getUser_avatar());
			SDViewBinder.setTextView(tvUser_name, model.getUser_name());
			SDViewBinder.setTextView(tvList_time, model.getTime());

			// 设置内容(表情)
			if (model.getParse_expres().size() != 0)
			{
				String b = model.getContent();
				String a = model.getScontent();
				for (int i1 = 0; i1 < model.getParse_expres().size(); i1++)
				{
					String c = "\\[\\w*" + model.getParse_expres().get(i1).getKey() + "\\]";// commentMysItems.get(l).getExpresList().get(i1).getKey();
																							// \[[衰]\]
					String g = "<img src='" + model.getParse_expres().get(i1).getValue() + "'/>";
					String e = a.replace(c, g);
					String d = b.replace(c, g);
					a = e;
					b = d;

					// 转变颜色

					if (a.contains("@"))
					{
						int tb = a.indexOf("@");
						int te = a.indexOf(":") + 1;
						if (tb < te)
						{
							String text_a = a.substring(tb, te);
							String ty = "<font color=red>" + text_a + "</font>";
							String tm = a.replace(text_a, ty);
							a = tm;
						}

					}
					if (b.contains("@"))
					{
						int tr = b.indexOf("@");
						int tf = b.indexOf(":") + 1;
						if (tr < tf)
						{
							String text_b = b.substring(tr, tf);
							String tk = "<font color=red>" + text_b + "</font>";
							String tp = b.replace(text_b, tk);
							b = tp;
						}
					}

					Spanned Stext = Html.fromHtml(a, new MyImageGetter(activity.getApplicationContext(), tvList_scontent), null);
					SDViewBinder.setTextView(tvList_scontent, Stext);
					Spanned text = Html.fromHtml(b, new MyImageGetter(activity.getApplicationContext(), tvList_content), null);
					SDViewBinder.setTextView(tvList_content, text);

				}
			} else if (model.getParse_expres().size() == 0)
			{

				String text1 = model.getContent();
				SDViewBinder.setTextView(tvList_content, text1);

				String text2 = model.getScontent();
				SDViewBinder.setTextView(tvList_content, text2);

			}

		}
		return convertView;
	}

	public class MyImageGetter implements ImageGetter
	{

		private Context context;
		private TextView tv;

		public MyImageGetter(Context context, TextView tv)
		{
			this.context = context;
			this.tv = tv;
		}

		@Override
		public Drawable getDrawable(String source)
		{

			String sdcardPath = Environment.getExternalStorageDirectory().toString(); // 获取SDCARD的路径

			// 最终图片保持的地址
			String savePath = sdcardPath + "/" + context.getPackageName() + "/" + source;

			File file = new File(savePath);
			if (file.exists())
			{
				// 如果文件已经存在，直接返回
				Drawable drawable = Drawable.createFromPath(savePath);
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth() + 15, drawable.getIntrinsicHeight() + 15);
				return drawable;
			}

			// 不存在文件时返回默认图片，并异步加载网络图片
			Resources res = context.getResources();
			URLDrawable drawable = new URLDrawable(res.getDrawable(R.drawable.nopic));
			new ImageAsync(drawable).execute(savePath, source);
			return drawable;

		}

		private class ImageAsync extends AsyncTask<String, Integer, Drawable>
		{

			private URLDrawable drawable;

			public ImageAsync(URLDrawable drawable)
			{
				this.drawable = drawable;
			}

			@Override
			protected Drawable doInBackground(String... params)
			{
				// TODO Auto-generated method stub
				String savePath = params[0];
				String url = params[1];

				InputStream in = null;
				try
				{
					// 获取网络图片
					HttpGet http = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = (HttpResponse) client.execute(http);
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
					in = bufferedHttpEntity.getContent();

				} catch (Exception e)
				{
					try
					{
						if (in != null)
							in.close();
					} catch (Exception e2)
					{
						// TODO: handle exception
					}
				}

				if (in == null)
					return drawable;

				try
				{
					File file = new File(savePath);
					String basePath = file.getParent();
					File basePathFile = new File(basePath);
					if (!basePathFile.exists())
					{
						basePathFile.mkdirs();
					}
					file.createNewFile();
					@SuppressWarnings("resource")
					FileOutputStream fileout = new FileOutputStream(file);
					byte[] buffer = new byte[4 * 1024];
					while (in.read(buffer) != -1)
					{
						fileout.write(buffer);
					}
					fileout.flush();

					Drawable mDrawable = Drawable.createFromPath(savePath);
					return mDrawable;
				} catch (Exception e)
				{
					// TODO: handle exception
				}
				return drawable;
			}

			@Override
			protected void onPostExecute(Drawable result)
			{
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null)
				{
					drawable.setDrawable(result);
					tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
				}
			}

		}
	}

	public class URLDrawable extends BitmapDrawable
	{

		private Drawable drawable;

		@SuppressWarnings("deprecation")
		public URLDrawable(Drawable defaultDraw)
		{
			setDrawable(defaultDraw);
		}

		private void setDrawable(Drawable nDrawable)
		{
			drawable = nDrawable;
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		}
	}

}
